//
//  StoryTableViewController.m
//  PetTown
//
//  Created by lanou3g on 15/5/30.
//  Copyright (c) 2015年 lanou3g. All rights reserved.
//

#import "StoryTableViewController.h"
#import "HomePageTableViewController.h"
#import "StoryPageCell.h"
#import "StoryDetailsTableViewController.h"
#import "StoryScrollPageViewController.h"
@interface StoryTableViewController ()
{
     MBProgressHUD * HUD;
}
@end

@implementation StoryTableViewController
- (void)viewDidLoad {
    [super viewDidLoad];

    
    NSArray * rrr = [NSArray arrayWithObjects:@"故事",@"萌宠榜", nil];
    UISegmentedControl * change = [[UISegmentedControl alloc] initWithItems:rrr];
    change.selectedSegmentIndex = 0;
    change.frame = CGRectMake(0, 15, 100, 25);
    
    [change addTarget:self action:@selector(changeView:) forControlEvents:UIControlEventValueChanged];
    
    self.navigationItem.titleView = change;

 
    //allDataArray开辟空间
    self.allDataArray = [[NSMutableArray alloc]init];
    
    self.title = @"故事";
    self.edgesForExtendedLayout = UIRectEdgeNone;
    [self returns];

    
    _b = 1;
    //下拉刷新
    [self.tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    //上啦刷新
    [self.tableView addFooterWithTarget:self action:@selector(footerRereshing)];

#warning message----注册
  // 注册需要的使用的cell
    [self.tableView registerNib:[UINib nibWithNibName:@"StoryPageCell" bundle:nil] forCellReuseIdentifier:@"storyCell"];
#pragma mark----数据解析
    [self storyPageJson];
   
}
//设置返回按钮
- (void)returns{
    UIButton * returnBu = [UIButton buttonWithType:(UIButtonTypeSystem)];
    UIBarButtonItem * leftBu = [[UIBarButtonItem alloc] initWithCustomView:returnBu];
    self.navigationItem.leftBarButtonItem = leftBu;
}

//下拉刷新
- (void)headerRereshing{
    
    [self.tableView headerEndRefreshing];
}
//上拉刷新
-(void)footerRereshing{
    _b++;
    [self storyPageJson];
    [self.tableView footerEndRefreshing];
}

- (void)changeView:(UISegmentedControl *)se{
    switch (se.selectedSegmentIndex) {
        case 0:{
            nil;
        }
            break;
        case 1:{
            MengwTableViewController * mengPTVC = [[MengwTableViewController alloc] init];
            [self.navigationController pushViewController:mengPTVC animated:YES];
            se.selectedSegmentIndex = 1;
            [self viewDidLoad];
        }
            break;
            
        default:
            break;
    }
}


#pragma mark----数据解析
- (void)storyPageJson
{
    HUD = [[MBProgressHUD alloc] initWithView:self.tableView];
    [self.tableView addSubview:HUD];
    HUD.labelText = @"正在加载";
    [HUD show:YES];

    NSString * str = [NSString stringWithFormat:StoryPageAPI,[NSString stringWithFormat:@"%d",_b]];
    NSURL * url = [NSURL URLWithString:str];
    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60.0];
    __weak StoryTableViewController * storyTVC = self;
    
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (data == nil) {
            return ;
        }
        
        NSMutableDictionary * dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSMutableDictionary * dic1 = dic[@"data"];
        NSArray * array = dic1[@"list"];
        for (NSDictionary * modelDic in array) {
            StoryPage * storyPage = [[StoryPage alloc]init];
            [storyPage setValuesForKeysWithDictionary:modelDic];
            
            [storyTVC.allDataArray addObject:storyPage];
        }
        [self.tableView reloadData];

       
    }];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    //清除缓存
    SDImageCache * sdI = [SDImageCache sharedImageCache];
    [sdI clearDisk];
    [sdI clearMemory];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete method implementation.
    // Return the number of rows in the section.
    return _allDataArray.count;
}

//cell高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 240;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    StoryPageCell *cell = [tableView dequeueReusableCellWithIdentifier:@"storyCell" forIndexPath:indexPath];
      // Configure the cell...
    
    
    StoryPage * story = _allDataArray[indexPath.row];
    cell.storyPage = story;
    cell.storyButton.tag = indexPath.row;
    [cell.storyButton addTarget:self action:@selector(didChickStoryDetails:) forControlEvents:UIControlEventTouchUpInside];
    
    //HUD = nil;
    [MBProgressHUD hideHUDForView:self.tableView animated:YES];
    
    return cell;
}

- (void)didChickStoryDetails:(UIButton *)BI
{
    StoryDetailsTableViewController * storyDetailsTVC = [[StoryDetailsTableViewController alloc]init];
    //
    StoryPage * story = _allDataArray[BI.tag];

    storyDetailsTVC.ppid = story.ppid;
    storyDetailsTVC.imgURL = story.photo;
    storyDetailsTVC.name = story.disname;

    
    [self.navigationController pushViewController:storyDetailsTVC animated:YES];
}

//点击Cell弹出故事版
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    StoryScrollPageViewController * storyScrollPageVC = [[StoryScrollPageViewController alloc] init];
    
    StoryPage * story = _allDataArray[indexPath.row];
    storyScrollPageVC.ppid = story.ppid;
    storyScrollPageVC.photoURL = story.photo;
      
    
    [self.navigationController pushViewController:storyScrollPageVC animated:YES];
    
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Table view delegate

// In a xib-based application, navigation from a table can be handled in -tableView:didSelectRowAtIndexPath:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here, for example:
    // Create the next view controller.
    <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:<#@"Nib name"#> bundle:nil];
    
    // Pass the selected object to the new view controller.
    
    // Push the view controller.
    [self.navigationController pushViewController:detailViewController animated:YES];
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
